package supplier

import (
	"encoding/json"
	"errors"
	"go-ddd/internal/common/core"
	plugin2 "go-ddd/internal/plugin"
	"go-ddd/internal/supplier/model"
)

type SupplierInterface interface {
	GetSupplierData(params string) (*model.SupplierDTO, error)
	GetSupplierName(params string) (string, error)
}

/*
业务逻辑层
*/
type SupplierApp struct {
	supplierRepo SupplierRepo
}

func NewSupplierApp(supplierApp SupplierRepo) SupplierInterface {
	return &SupplierApp{
		supplierRepo: supplierApp,
	}
}
func (s *SupplierApp) GetSupplierName(params string) (string, error) {

	plugin := core.GetSupplierPlugin(params + ".so")
	// 获取SupplierTrans
	p, err := plugin.GetPlugin().Lookup("NewSupplierTrans")
	if err != nil {
		return "", err
	}
	supplierTrans := p.(func() plugin2.SupplierTransInterface)
	return supplierTrans().Name()

}

func (s *SupplierApp) GetSupplierData(params string) (*model.SupplierDTO, error) {
	var err error
	//先确定类型
	var paramsMap map[string]interface{}
	json.Unmarshal([]byte(params), paramsMap)
	//确定对接平台类型 并进行对接操作
	name, ok := paramsMap["name"]
	if !ok {
		return nil, errors.New("未找到组件")
	}
	// 获取已经载入的插件
	plugin := core.GetSupplierPlugin(name.(string) + ".so")
	// 获取SupplierTrans
	p, err := plugin.GetPlugin().Lookup("NewSupplierTrans")
	if err != nil {
		return nil, err
	}
	supplierTrans := p.(func() plugin2.SupplierTransInterface)
	path, err := supplierTrans().Path()
	if err != nil {
		return nil, err
	}
	method, err := supplierTrans().Method()
	if err != nil {
		return nil, err
	}
	var body []byte
	switch method {
	case core.GET:
		body, err = s.supplierRepo.GET(path, params)
		if err != nil {
			return nil, err
		}
		break
	case core.POST:
		return nil, errors.New("暂不支持")
		break
	default:
		return nil, errors.New("没有输入类型")
	}
	return supplierTrans().Transform(body)
}
